<template>
  <div class="container">
    <div class="bgPic">
      <div class="bg-blue">
        <el-row class="uploadcol" :gutter="20">
          <el-col>
            <el-upload
              ref="upload"
              class="upload-demo"
              action="/api/credit_risk_input/"
              :limit="1"
              :on-exceed="handleExceed"
              :on-success="handleSuccess"
              :on-error="handleError"
              :before-upload="beforeUpload"
              :auto-upload="false"
            >
              <template #trigger>
                <el-button type="primary">选择文件</el-button>
              </template>
              <el-button class="ml-3" type="success" @click="submitUpload">
                上传到服务器
              </el-button>
              <template #tip>
                <div class="el-upload__tip text-red">
                  每次只能选择一个文件，如果重复上传会覆盖文件
                </div>
              </template>
            </el-upload>
          </el-col>
        </el-row>
        <el-row class="uploadcol" :gutter="20">
          <el-col>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="每次评估都会使用最近上传的文件，数据会累积"
              placement="left"
            >
              <el-button type="primary" @click="startEvaluation">
                开始评估
              </el-button>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="删除服务器的所有评估数据记录"
              placement="right"
            >
              <el-button type="warning" @click="resetEvaluation">
                评估数据重置
              </el-button>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-row class="skl3" :gutter="20">
          <el-col>
            <el-table
              :data="data.table.tableData"
              style="width: 100%"
              height="400px"
            >
              <el-table-column prop="name" label="公司名称" />
              <el-table-column prop="index" label="评估结果" />
              <el-table-column prop="predict" label="风险概率" />
            </el-table>
          </el-col>
          <div class="pt1">
            <el-pagination
              class="elp1"
              background
              layout="prev, pager, next"
              :total="data.table.total"
              :page-size="data.table.pageSize"
              @current-change="pageChange"
            />
          </div>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import "../../css/jquery.bxslider.css";
import "../../css/font-awesome.min.css";
import "../../css/bootstrap.min.css";
import "../../css/animate.css";
import "../../css/style.css";

import { onMounted, reactive, ref } from "vue";
import { genFileId, ElMessage } from "element-plus";

import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import axios from "axios";

const upload = ref<UploadInstance>();
let data = reactive({
  table: {
    tableData: [],
    page: 2,
    pageSize: 20,
    total: 100,
  },
});

onMounted(() => {
  getPage();
});

const beforeUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log(rawFile);
  if (
    rawFile.type == "application/vnd.ms-excel" ||
    rawFile.type == "text/csv"
  ) {
    return true;
  }
  ElMessage.error("文件必须为 xls 或 csv 格式!");
  return false;
};

const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};

const handleSuccess: UploadProps["onSuccess"] = (
  response: any,
  uploadFile,
  uploadFiles
) => {
  ElMessage({
    message: "上传成功！",
    type: "success",
  });
};

const handleError: UploadProps["onError"] = (
  error: Error,
  uploadFile,
  uploadFiles
) => {
  ElMessage({
    message: "上传失败：" + error.name,
    type: "warning",
  });
};

const submitUpload = () => {
  upload.value!.submit();
};

const startEvaluation = () => {
  console.log("Starting evaluation");
  getEvaluation();
  setTimeout(getPage, 2000);
};

const getEvaluation = () => {
  axios.post("/api/create_risk_evlation/", {}).catch(function (error) {
    ElMessage({
      message: "评估失败：" + error.name,
      type: "warning",
    });
  });
};

const resetEvaluation = () => {
  console.log("Resetting evaluation");
  axios
    .post("/api/reset_evaluation/", {})
    .then(function (response) {
      ElMessage({
        message: "重置成功！",
        type: "success",
      });
      getPage();
    })
    .catch(function (error) {
      ElMessage({
        message: "重置失败：" + error.name,
        type: "warning",
      });
    });
};

const getPage = () => {
  data.table.tableData = [];
  axios
    .post("/api/page_query_for_evaluation/", {
      page: data.table.page,
      pageSize: data.table.pageSize,
    })
    .then(function (response) {
      data.table.total = response.data.total;
      console.log(response.data);
      let datalist = response.data.list;
      for (let i = 0; i < datalist.length; i++) {
        let name = datalist[i].fields.name;
        let index = "有风险";
        let predict = datalist[i].fields.predict;
        if (datalist[i].fields.index == 0) {
          index = "无风险";
        }
        data.table.tableData.push({
          name: name,
          index: index,
          predict: predict,
        });
      }
      ElMessage({
        message: "数据拉取成功！",
        type: "success",
      });
    })
    .catch(function (error) {
      ElMessage({
        message: "表格读取失败，请保证已经上传数据并评估 " + error.name,
        type: "warning",
      });
      console.log(error);
    });
};

const pageChange = (pageNumber: any) => {
  console.log(pageNumber);
  data.table.page = pageNumber;
  getPage();
};
</script>

<style>
.ml-3 {
  margin-left: 20px;
}
.bg-blue {
  padding: 20px 0 30px 0;
  background-color: #ecf5ff;
}
input[type="file"] {
  display: none !important;
}
.upload-demo {
  width: 360px;
}
.intro-text {
  color: #fff;
}
.intro {
  background-color: #ffffff;
  font-size: 20px;
  height: 300px;
}
.uploadcol {
  padding: 20px;
  padding-left: 35%;
}
.skl3 {
  padding-bottom: 20px;
}

.pt1 {
  width: 100%;
  height: 100px;
  text-align: center;
  position: relative;
}
.el-pagination {
  width: 50%;
  height: 50%;
  overflow: auto;
  margin: auto;
  position: absolute;
  top: 0px;
  left: 0;
  bottom: 0;
  right: 0;
}
</style>
